namespace MessageBroker.tests

import System
import MessageBroker
import MessageBroker.Client
import MessageBroker.Server
import System.Collections
import NUnit.Framework

[TestFixture]
class AsyncTests:
"""Description of AsyncTests"""

	firstSubscription = "la mia prima coda"
	emptySubscription = "una coda vuota"
	massiveSubscription = "coda piena di roba"
	referralName = "ciao sono io..."
	firstSharedQueue = "firstSharedQueue"
	broker = Broker(
				SharedQueues: 
					{
					"firstSharedQueue":
						SharedQueue(
							Name: "firstSharedQueue"
							)
					}
			    )
	client = BrokerClient(
				Server:broker, 
				InstanceName: 
				referralName, 
				MessagesPerPage: 50, 
				UseBufferedSending: true
				)

	client2 = BrokerClient(
				Server:broker, 
				InstanceName: 
				referralName + "#2", 
				MessagesPerPage: 1000, 
				UseBufferedSending: true
				)

	[TestFixtureSetUp]
	def setup():
		broker.CreateSubscription(firstSubscription, referralName + "#2")
		broker.CreateSubscription(massiveSubscription, referralName + "#2")
		broker.CreateSubscription(emptySubscription, referralName + "#2")
		client.Send(firstSubscription, Message(Subject:"test", Body: "test body"))
		client2.ReceivedMessages += def(messages as IList):
			print "received ${messages.Count} messages (${client2.ReceivedMessagesCount}/${client.SentMessagesCount})"
		client2.PollEvery = 1
		client2.Listen()
		
	[TestFixtureTearDown]
	def tearDown():
		print "sono stati mandati ${client.SentMessagesCount} messaggi"
		while client.SentMessagesCount > client2.ReceivedMessagesCount:
			Threading.Thread.Sleep(100)
		client2.Cancel()
		print "sono stati ricevuti ${client2.ReceivedMessagesCount} messaggi"
		
	def sendMessage(subject as string):
		client.Send(massiveSubscription, Message(Subject:"subject ${subject}", Body: "test body"))
		
	def doManyMessages(many as int):
		for i in range(many):
			sendMessage("test numero ${i}")
		client.Flush()

	[Test]
	def do1000Messages():
		doManyMessages(1000)

	[Test]
	def do10000Messages():
		doManyMessages(10000)

	[Test]
	def do100000Messages():
		doManyMessages(100000)
		
	[Test]
	def sendSomeSharedMessages():
		for n in range(1000):
			client.Send(firstSharedQueue, Message(Subject: "SQ ${n}"))
		client.Flush()
		
